package com.etone.smartAudit.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.etone.smartAudit.domain.Admin;
import com.etone.smartAudit.domain.ProjectFile;
import com.etone.smartAudit.domain.ProjectFileVersion;
import com.etone.smartAudit.mapper.ProjectFileVersionMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.channels.FileChannel;
import java.nio.file.StandardCopyOption;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 文件版本记录 文件版本记录 服务实现类
 * </p>
 *
 * @author jiayen
 * @since 2021-05-08
 */
@Slf4j
@Service
public class ProjectFileVersionService extends ServiceImpl<ProjectFileVersionMapper, ProjectFileVersion> {

    @Value("${audit.filePath}")
    private String filePath;

    @Autowired
    private ProjectFileService fileService;

    /***
     * 复制一个历史版本
     * @param file
     */

    @Transactional(rollbackFor = Exception.class)
    public void copyVersion(ProjectFile file, Admin admin) {

        //copy文件
        File realFile = new File(filePath + file.getPath());
        StringBuilder newFilePath = new StringBuilder();
        String dateStr = DateUtil.format(new Date(), "yyyyMMddHHmmssSSS");
        StringBuilder newFilName = new StringBuilder();
        //获取上一份备份的版本号
        ProjectFileVersion version = baseMapper.getlastVerion(file.getId());
        if (realFile.exists()) {
            newFilName.append(file.getFileName().substring(0, file.getFileName().lastIndexOf("."))).append("_").append(version == null ? 1 : (version.getVersion() == null ? 1 : version.getVersion()) + 1).append(".")
                    .append(file.getExtName());
            //复制文件
            newFilePath.append(filePath).append("/").append(DateUtil.format(new Date(), "yyyyMMdd")).append(newFilName);
            copyFile(realFile.getAbsolutePath(), newFilePath.toString());
        }

        ProjectFileVersion fileVersion = ProjectFileVersion.builder()
                .fileId(file.getId())
                .createdBy(admin.getId())
                .createdName(admin.getNickName())
                .version(version == null ? 1 : (version.getVersion() == null ? 1 : version.getVersion()) + 1)
                .updatedTime(new Date())
                .createdTime(new Date())
                .hash(fileService.getHash(realFile.getAbsolutePath()))
                .size(realFile.length())
                .updatedBy(admin.getId())
                .updatedName(admin.getNickName())
                .fileName(newFilName.toString())
                .path(newFilePath.toString().replace(filePath, ""))
                .build();
        this.save(fileVersion);
    }

    /***
     * copy文件
     * @param from
     * @param to
     */
    public void copyFile(String from, String to) {
        FileUtil.copyFile(from, to, StandardCopyOption.REPLACE_EXISTING);
//        FileChannel input = null;
//        FileChannel output = null;
//        try {
//            input = new FileInputStream(from).getChannel();
//            output = new FileOutputStream(to).getChannel();
//            output.transferFrom(input, 0, input.size());
//        } catch (Exception e) {
//            log.debug("复制文件" + "copyFile", "error occur while copy", e);
//        } finally {
//            try {
//                input.close();
//                output.close();
//            } catch (IOException e) {
//                log.error("关闭流失败!", e);
//            }
//
//        }
    }

    /***
     * 获取指定文件的历史版本
     * @param fId
     * @return
     */
    public List<ProjectFileVersion> getList(Integer fId) {
        LambdaQueryWrapper<ProjectFileVersion> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProjectFileVersion::getFileId, fId).orderByDesc(ProjectFileVersion::getCreatedTime);
        return this.list(queryWrapper);
    }

    public static void main(String[] args) throws Exception {
        String file = "D:\\woapi\\upload\\2\\1620698426795_82013.xlsx";
        File realFile = new File(file);
        System.out.println("path:" + realFile.getPath());
        System.out.println("parent:" + realFile.getParentFile().getName());
        System.out.println("格式化:" + file.replace("D:\\woapi\\upload", ""));
        System.out.println("格式化新名称:" + DateUtil.format(new Date(), "yyyyMMddHHmmssSSS"));

//        String fileNew = "D:\\woapi\\upload\\2\\1620698426795_82013_copy.xlsx";
//        copyFile(file, fileNew);
        System.out.println(URLDecoder.decode("http%3A%2F%2Fdoc.jiayen.cn%2Fwopi%2Ffiles%2FL3BwdC8xNjIwODEyMzU3NDk3XzMwNDQ4LnBwdA%3D%3D%3FuserName%3D5bCP5p6X5ZCM5a2m%26key%3D43833470ebc9b0c307ca721575f588e9", "utf-8"));
    }
}
